package com.demo.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DatabaseConfig {
    private static final Logger log = LogManager.getLogger(DatabaseConfig.class);
    private static HikariDataSource dataSource;

    // 静态初始化块，确保连接池在类加载时初始化
    // 静态初始化块
    static {
        try {
            // 1. 加载配置文件
            Properties props = new Properties();
            try (InputStream input = DatabaseConfig.class.getClassLoader().getResourceAsStream("api.properties")) {
                if (input == null) {
                    throw new RuntimeException("找不到 api.properties 配置文件");
                }
                props.load(input);
            }

            // 2. 读取数据库配置
            String url = props.getProperty("db.url");
            String username = props.getProperty("db.username");
            String password = props.getProperty("db.password");
            String driver = props.getProperty("db.driver");

            // 3. 初始化连接池
            init(url, username, password, driver);
        } catch (Exception e) {
            log.error("数据库连接池初始化失败", e);

        }
    }

    /**
     * 初始化数据库连接池
     */
    public static void init(String url, String username, String password, String driver) {
        try {
            // 显式加载驱动类
            Class.forName(driver);
            log.info("成功加载MySQL驱动: {}", driver);
        } catch (ClassNotFoundException e) {
            log.error("MySQL驱动类未找到: {}", driver, e);
            throw new RuntimeException("MySQL驱动类未找到: " + driver, e);
        }

        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(url);
        config.setUsername(username);
        config.setPassword(password);
        config.setDriverClassName(driver);

        // 连接池配置
        config.setMaximumPoolSize(10);
        config.setMinimumIdle(5);
        config.setConnectionTimeout(30000);
        config.setIdleTimeout(600000);
        config.setMaxLifetime(1800000);

        dataSource = new HikariDataSource(config);
        log.info("数据库连接池初始化完成");
    }

    /**
     * 获取数据源
     */
    public static DataSource getDataSource() {
        if (dataSource == null || dataSource.isClosed()) {
            throw new IllegalStateException("数据库连接池未初始化或已关闭");
        }
        return dataSource;
    }

    /**
     * 测试数据库连接
     */
    public static void testConnection() {
        try (Connection conn = getDataSource().getConnection()) {
            if (conn != null && !conn.isClosed()) {
                log.info("成功连接到数据库: {}", conn.getMetaData().getURL());
            }
        } catch (SQLException e) {
            log.error("数据库连接测试失败", e);
            throw new RuntimeException("数据库连接测试失败", e);
        }
    }

    /**
     * 关闭连接池
     */
    public static void close() {
        if (dataSource != null && !dataSource.isClosed()) {
            dataSource.close();
            log.info("数据库连接池已关闭");
        }
    }
}


